'use strict';

const BuildTree =function (objList,parentId) {
    if(!parentId)
        parentId = 'pid';
    for(let i= objList.length-1;i>-1;i--){
        let obj = objList[i];
        if(obj[parentId]){
            let pObj = FindObjById(objList,obj[parentId]);
            if(pObj){
                // delete obj[parentId];
                pObj.children = pObj.children||[];
                pObj.children.push(obj);
                objList.splice(i,1);
            }
        }
    }
    return objList;
};

const FindObjById = function (objList,id) {
    for(let i=0;i<objList.length;i++){
        let obj = objList[i];
        if(obj.ID.toString() === id.toString()){
            return obj;
        }else if(obj.children && obj.children.length>0){
            let findObj =FindObjById(obj.children,id);
            if(findObj)
                return findObj;
        }
    }
}

const handler = (req, res, next) => {
    req.mongo.collection('area').find({ID:{$ne:'100000'}}).toArray((e,r)=> {
        if (e) return res.err.mongoError();
        let tree = BuildTree(r,'ParentId');
        res.reply({code:0,message:"查询成功",data:tree});
    });
};

module.exports = {
    description:'获取省市区代码树形结构',
    open:true,
    handler: handler
};
